package captcha

import (
	"bytes"
	"fmt"
	"path"
	"strings"
	"github.com/gofiber/fiber/v2"
	"github.com/dchest/captcha"
)

type CaptchaResponse struct {
	CaptchaId string `json:"captchaId"` //验证码Id
	ImageUrl  string `json:"imageUrl"`  //验证码图片url
}

func Captcha(c *fiber.Ctx) error{
	length := captcha.DefaultLen
	captchaId := captcha.NewLen(length)
	var captcha CaptchaResponse
	captcha.CaptchaId = captchaId
	captcha.ImageUrl = "/captcha/" + captchaId + ".png"
	return c.JSON(captcha)
}
func CaptchaImage(c *fiber.Ctx) error {
	captchaId := c.Params("captchaId")
		fmt.Println("GetCaptchaPng : " + captchaId)
		return ServeHTTP(c)
}
func Verify(c *fiber.Ctx) {
	captchaId := c.FormValue("captchaId")
	value := c.FormValue("value")
	if captchaId == "" || value == "" {
		c.SendString("参数错误")
	}
	if captcha.VerifyString(captchaId, value) {
		c.SendString("验证成功")
	} else {
		c.SendString("验证失败")
	}
}
func ServeHTTP(c *fiber.Ctx) error {
	dir, file := path.Split(c.Path())
	ext := path.Ext(file)
	id := file[:len(file)-len(ext)]
	fmt.Println("file : " + file)
	fmt.Println("ext : " + ext)
	fmt.Println("id : " + id)
	if ext == "" || id == "" {
		// http.NotFound(w, r)
		return c.SendString("404 Not Found")
	}
	fmt.Println("reload : " + c.FormValue("reload"))
	if c.FormValue("reload") != "" {
		captcha.Reload(id)
	}
	lang := strings.ToLower(c.FormValue("lang"))
	download := path.Base(dir) == "download"
	if Serve(c, id, ext, lang, download, captcha.StdWidth, captcha.StdHeight) == captcha.ErrNotFound {
		// http.NotFound(w, r)
		return c.SendString("404 Not Found")
	}
	return Serve(c, id, ext, lang, download, captcha.StdWidth, captcha.StdHeight)
}
func Serve(c *fiber.Ctx, id, ext, lang string, download bool, width, height int) error {
	c.Set("Cache-Control", "no-cache, no-store, must-revalidate")
	c.Set("Pragma", "no-cache")
	c.Set("Expires", "0")

	var content bytes.Buffer
	switch ext {
	case ".png":
		c.Set("Content-Type", "image/png")
		captcha.WriteImage(&content, id, width, height)
	case ".wav":
		c.Set("Content-Type", "audio/x-wav")
		captcha.WriteAudio(&content, id, lang)
	default:
		return captcha.ErrNotFound
	}

	if download {
		c.Set("Content-Type", "application/octet-stream")
	}
	 c.Write(content.Bytes())
	// http.ServeContent(w, r, id+ext, time.Time{}, bytes.NewReader(content.Bytes()))
	return nil
}
